import React, {useEffect, useRef, useState} from "react";
import type {PaymentLogItem} from "@/pages/PaymentLogs/data";
import {Avatar, Divider, message} from "antd";
import {deletePaymentLog, queryPaymentLog, updatePaymentLog, updatePaymentRefund} from "@/pages/PaymentLogs/service";
import dayjs from "dayjs";
import UpdateForm from "@/pages/PaymentLogs/components/UpdateForm";
import RefundForm from "@/pages/PaymentLogs/components/RefundForm";
import {queryFamily, queryPayment} from "@/pages/User/Account/settings/components/service";
import type { DropdownRef} from "antd-mobile";
import {Button, Dialog, DotLoading, Dropdown, InfiniteScroll, List, SwipeAction, Toast} from "antd-mobile";
import Style from "./style.less"

/**
 * 删除节点
 *
 * @param record
 */

const handleSingleRemove = async (record: any) => {
  const hide = message.loading('正在删除');
  try {
    const res = await deletePaymentLog({
      key: record.id,
    });
    hide();
    if (res) {
      if (res.status === 'done') {
        Toast.show({
          content: res.message,
          icon: "success"
        })
        return true;
      } else {
        Toast.show({
          content: res.message,
          icon: "fail"
        })
        return false;
      }
    } else {
      Toast.show({
        content: '请求超时，请稍后重试',
        icon: "fail"
      })
      return false;
    }
  } catch (error) {
    hide();
    Toast.show({
      content: '删除失败，请重试',
      icon: "fail"
    })
    return false;
  }
};

/**
 * 更新节点
 *
 * @param fields
 * @param currentRow
 */

const handleUpdate = async (fields: any, currentRow?: PaymentLogItem) => {
  const hide = message.loading('正在修改');

  try {
    const res = await updatePaymentLog({
      id: currentRow?.id,
      ...fields,
    });
    if(res && res.status === "done" ){
      hide();
      Toast.show({
        content: res.message,
        icon: "success"
      })
      return true;
    }else {
      hide()
      Toast.show({
        content: res.message,
        icon: "fail"
      })
      return false;
    }
  } catch (error) {
    hide();
    message.error('更新失败，请重试！');
    return false;
  }
};

/**
 * 更新节点
 *
 * @param fields
 * @param currentRow
 */

const handleRefund = async (fields: any, currentRow?: PaymentLogItem) => {
  const hide = message.loading('正在处理');

  try {
    const res = await updatePaymentRefund({
      id: currentRow?.id,
      ...fields,
    });
    if(res && res.status === "done" ){
      hide();
      Toast.show({
        content: res.message,
        icon: "success"
      })
      return true;
    }else {
      hide()
      Toast.show({
        content: res.message,
        icon: "fail"
      })
      return false;
    }
  } catch (error) {
    hide();
    message.error('更新失败，请重试！');
    return false;
  }
};

export type Props = {
  update: boolean;
};

const PaymentLogs: React.FC<Props> = (props: {update: boolean}) => {
  /** 更新窗口的弹窗 */
  const [currentRow, setCurrentRow] = useState<PaymentLogItem>();
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [refundModalVisible, handleRefundModalVisible] = useState<boolean>(false);
  const [typeDataSource, setTypeDatasource] = useState<any[]>([])
  const [familyDataSource, setFamilyDatasource] = useState<any[]>([])

  // 家庭成员，支出类型筛选
  const dropdownRef = useRef<DropdownRef>(null)

  const [familyId, setFamilyId] = useState(0)
  const [paymentId, setPaymentId] = useState(0)
  const [familyTitle, setFamilyTitle] = useState("成员筛选")
  const [paymentTitle, setPaymentTitle] = useState("支出类型")

  // 从后台获取用户对象数据
  useEffect(() => {
    queryFamily().then((res)=>{
      if (res.status === "done"){
        // 数据获取成功
        // 整理list为prolist对象
        const data = [...familyDataSource];

        // 先清空
        data.splice(0, data.length)

        // 填充新数据
        // eslint-disable-next-line array-callback-return
        res.data?.map((item: {name: string, id: number})=>{
          data.push({
            label: item.name,
            value: item.id,
          })
        })
        setFamilyDatasource(data)
      }
    })
  }, []);

  // 从后台获取支出分类数据
  useEffect(() => {
    queryPayment().then((res)=>{
      if (res.status === "done"){
        // 数据获取成功
        // 整理list为prolist对象
        const data = [...typeDataSource];

        // 先清空
        data.splice(0, data.length)

        // 填充新数据
        // eslint-disable-next-line array-callback-return
        res.data?.map((item: {name: string, id: number})=>{
          data.push({
            label: item.name,
            value: item.id,
          })
        })
        setTypeDatasource(data)
      }
    })
  }, []);

  // 获取流水数据
  const [page, setPage] = useState(1)
  const [data, setData] = useState<PaymentLogItem[]>(new Array())
  const [hasMore, setHasMore] = useState(true)

  async function loadMore(firstPage = false) {

    let currentPage = page
    if (firstPage){
        currentPage = 1
    }

    // 从后台获取流水
    const res = await queryPaymentLog({
      current: currentPage, pageSize: 10, type: paymentId, family: familyId
    });
    if (res.status === "done"){
      if (currentPage === 1){

        // 重载数据
        const emptyList = [...data]
        emptyList.splice(0, emptyList.length)
        res.data?.map((item)=>{
          emptyList.push(item)
        })
        setData(emptyList)
      }else {

        // 插入数据
        const newData = [...data];
        res.data?.map((item)=>{
          newData.push(item)
        })
        setData(newData)
      }

      // 计算是否有下一页
      setHasMore(res.total > 10 * currentPage)

      // 下一页
      setPage(currentPage + 1)
    }
    console.log(page,data, "after")
  }

  // 更新数据
  const [needUpdate, setNeedUpdate] = useState(false)
  useEffect(()=>{
    loadMore(true)
  }, [props, needUpdate, paymentId, familyId])


  // 自定义下拉获取
  // eslint-disable-next-line @typescript-eslint/no-shadow
  const InfiniteScrollContent = ({ hasMore }: { hasMore?: boolean }) => {
    return (
      <>
        {hasMore ? (
          <>
            <span>Loading</span>
            <DotLoading />
          </>
        ) : (
          <span>--- 我是有底线的 ---</span>
        )}
      </>
    )
  }

  // 滑动操作
  const rightActions: any[] = [
    {
      key: 'edit',
      text: '修改',
      color: '#1890ff',
      onClick: ()=>{
        handleUpdateModalVisible(true)
      }
    },
    {
      key: 'refund',
      text: '退款',
      color: 'warning',
      onClick: ()=>{
        handleRefundModalVisible(true)
      }
    },
    {
      key: 'delete',
      text: '删除',
      color: 'danger',
      onClick: ()=>{
        Dialog.show({
          content: "真的要删除？",
          closeOnAction: true,
          actions: [
            [
              {
                key: 'cancel',
                text: '取消',
              },
              {
                key: 'delete',
                text: '删除',
                bold: true,
                danger: true,
                onClick: async ()=>{
                  // 执行删除操作
                  const success = await handleSingleRemove(currentRow);
                  if (success) {
                    // 删除成功，从data中删除此行数据
                    const newData = [...data]
                    newData.map((item)=>{
                      if (item.id == currentRow?.id){
                        // 删除
                        newData.splice(newData.indexOf(item), 1)
                        setData(newData)
                      }
                    })
                  }
                }
              },
            ],
          ]
        })

      }
    },
  ]

  return (
    <>
      <div style={{width: `100%`}}>
        <Dropdown
          style={{position: "relative", top: 46, width: `100%`, zIndex: 999}}
          ref={dropdownRef}
        >
          <Dropdown.Item
            key='familyOption'
            title={familyTitle}
            destroyOnClose
          >
            <div style={{ padding: 12 }}>
              {familyDataSource.map((item)=>(
                <>
                  <Button
                    key={"family_" + item.value}
                    style={{color: "black", width: `100%`, padding: 5}}
                    onClick={()=>{
                      setPage(1)
                      setFamilyId(item.value)
                      setFamilyTitle(item.label)
                      dropdownRef.current?.close()
                    }}
                  >
                    {item.label}
                  </Button>
                  <br/>
                </>
              ))}
              <Button
                key={"family_reset"}
                style={{color: "black", width: `100%`, padding: 5}}
                onClick={()=>{
                  setPage(1)
                  setFamilyId(0)
                  setFamilyTitle("成员筛选")
                  dropdownRef.current?.close()
                }}
              >
                所有成员
              </Button>
            </div>
          </Dropdown.Item>
          <Dropdown.Item
            key='payOption'
            title={paymentTitle}
            destroyOnClose
          >
            <div style={{ padding: 12 }}>
              {typeDataSource.map((item)=>(
                <>
                  <Button
                    key={"type_" + item.value}
                    style={{color: "black", width: `100%`, padding: 5}}
                    onClick={()=>{
                      setPage(1)
                      setPaymentId(item.value)
                      setPaymentTitle(item.label)
                      dropdownRef.current?.close()
                    }}
                  >
                    {item.label}
                  </Button>
                  <br/>
                </>
              ))}
              <Button
                key={"type_reset"}
                style={{color: "black", width: `100%`, padding: 5}}
                onClick={()=>{
                  setPage(1)
                  setPaymentId(0)
                  setPaymentTitle("支出类型")
                  dropdownRef.current?.close()
                }}
              >
                所有支出类型
              </Button>
            </div>
          </Dropdown.Item>
        </Dropdown>
        <Divider/>
        <List
          style={{
            position: "relative",
            width: `100%`,
            "--font-size": "15px"
        }}
        >
          {data.map((item) => {
            if (item.date) {
              // 有日期的，插入一个日期列
              return (
                <>
                  <List.Item key={"item_" + item.id} className={Style.itemBackground}>
                    <div className={Style.inlineBlock}>
                      <b className={Style.days}>{dayjs(item.date).format("DD ")}</b>
                    </div>
                    <div className={Style.monthAndYear}>
                      {dayjs(item.date).format("/ MM / YYYY")}
                    </div>
                  </List.Item>
                  <SwipeAction
                    key={item.id}
                    rightActions={rightActions}
                    onActionsReveal={() => {
                      setCurrentRow(item)
                    }}
                  >
                    <List.Item
                      key={"item" + item.id}
                      prefix={<Avatar src={"/static/icons/" + item.payType?.icon}/>}
                      description={<span>{dayjs(item.time).format("HH:mm")}</span>}
                      extra={
                      <>
                        <a
                          className={Style.itemContent}
                        >
                          <Avatar
                            style={{width: 28, height: 28}}
                            src={"/static/icons/" + item.familyType?.icon}
                          />
                          {item.remark.length > 0 ?
                            <span >{item.familyType?.name}<p style={{color: "#8c8c8c", fontSize: 8}}>{item.remark.length > 0 ? item.remark : ""}</p></span> :
                            <span style={{paddingTop: 5}}>{item.familyType?.name}</span>
                          }

                        </a>
                        <a
                          onClick={()=>{Toast.show({content: "这是消费金额。"})}}
                          className={Style.outMoney}
                        >
                          ¥ {item.money}
                        </a>
                        <a
                          onClick={()=>{Toast.show({content: "这是退款金额。"})}}
                          className={Style.refundMoney}
                        >
                          ¥ {item.refund}
                        </a>
                      </>
                      }
                    >
                      {item.payType?.name}
                    </List.Item>
                  </SwipeAction>
                </>
              )
            }else{

              // 同一天的不同时间的，只返回时间的
              return (
                <SwipeAction
                  key={item.id}
                  rightActions={rightActions}
                  onActionsReveal={() => {
                    setCurrentRow(item)
                  }}
                >
                  <List.Item
                    key={item.id}
                    prefix={<Avatar src={"/static/icons/" + item.payType?.icon}/>}
                    description={<span>{dayjs(item.time).format("HH:mm")}</span>}
                    extra={
                      <>
                        <a className={Style.itemContent}>
                          <Avatar style={{width: 28, height: 28}} src={"/static/icons/" + item.familyType?.icon}/>
                          {item.remark.length > 0 ?
                            <span >{item.familyType?.name}<p style={{color: "#8c8c8c", fontSize: 8}}>{item.remark.length > 0 ? item.remark : ""}</p></span> :
                            <span style={{paddingTop: 5}}>{item.familyType?.name}</span>
                          }
                        </a>

                        <a
                          onClick={()=>{Toast.show({content: "这是消费金额。"})}}
                          className={Style.outMoney}
                        >
                          ¥ {item.money}
                        </a>
                        <a
                          onClick={()=>{Toast.show({content: "这是退款金额。"})}}
                          className={Style.refundMoney}
                        >
                          ¥ {item.refund}
                        </a>
                      </>
                    }
                  >
                    {item.payType?.name}
                  </List.Item>
                </SwipeAction>
              )
            }
          })}
        </List>
        <InfiniteScroll
          loadMore={loadMore}
          hasMore={hasMore}
          threshold={0}
        >
          <InfiniteScrollContent hasMore={hasMore} />
        </InfiniteScroll>
        <div style={{height: 100, width: `100%`, position: "relative"}}/>
      </div>

      <UpdateForm
        onCancel={()=>{
          handleUpdateModalVisible(false)
          setCurrentRow(undefined)
        }}
        onSubmit={async (value)=>{
          const success = await handleUpdate(value, currentRow);
          if (success){
            handleUpdateModalVisible(false)
            setCurrentRow(undefined)

            // 更新数据
            setNeedUpdate(!needUpdate)
          }
        }}
        modalVisible={updateModalVisible}
        values={currentRow || {}}
      />
      <RefundForm
        onCancel={()=>{
          handleRefundModalVisible(false)
          setCurrentRow(undefined)
        }}
        onSubmit={async (value)=>{
          const success = await handleRefund(value, currentRow);
          if (success){
            handleRefundModalVisible(false)
            setCurrentRow(undefined)

            // 更新数据
            setNeedUpdate(!needUpdate)
          }
        }}
        modalVisible={refundModalVisible}
        values={currentRow || {}}
      />
    </>
  )
}
export default PaymentLogs;
